﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using ViewModels;

namespace SignalRTest.Controllers
{
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public async Task<JsonResult> DoLogin(string name)
        {
            //ASP.NET Core 中的基于声明的授权
            string userId = Guid.NewGuid().ToString().Replace("-", "");

            var userInfo = new UserInfo(name, userId);

            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name,userInfo.UserName),   
                new Claim(ClaimTypes.NameIdentifier,userInfo.UserId)  
            };

            
            var indentity = new ClaimsIdentity(claims, "formlogin");
            var principal = new ClaimsPrincipal(new[] { indentity});



            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                IsPersistent = false,
                AllowRefresh = false
            });

            //验证是否授权成功
            if (principal.Identity.IsAuthenticated)
            {
                return Json(new { error = false });
            }
            else
                return Json(new { error = true });
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> logOff()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            return Redirect("/Home/Index");
        }
    }
}
